本次主題是以colab的環境進行學習的,在本篇文章中,我將講解影像辨識的基礎技能在接下來的文章中這些技能將多次出現,先讀過這些語法再繼續去看後面的文章會比較能快速上手喔。依照進度每個禮拜都會記錄不同的影像辨識方法,基本順序會從:
在我們上一篇文章中我們已經把資料集準備好了,接下來我們就回到colab裡面進行模型訓練吧。
雲端硬碟掛載:
from google.colab import drive
drive.mount('/content/drive')
模型訓練:
將雲端硬碟掛載好之後,我們就可以開始訓練模型了。後面文章會再補充模型的介紹以及模型的堆疊。在訓練好模型之後我們會將模型儲存到雲端硬碟,方便下次直接使用模型。
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
import pathlib
import glob
import matplotlib.pyplot as plt
import numpy as np
import os
import PIL
import PIL.Image as Image
import joblib
os.environ['TF_XLA_FLAGS'] = '--tf_xla_enable_xla_devices'
data_dir = pathlib.Path("/content/drive/MyDrive/train_data")
batch_size = 32
img_height = 180
img_width = 180
train_ds = tf.keras.utils.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="training",
seed=3,
image_size=(img_height, img_width),
batch_size=batch_size)
val_ds = tf.keras.utils.image_dataset_from_directory(
data_dir,
validation_split=0.8,
subset="validation",
seed=3,
image_size=(img_height, img_width),
batch_size=batch_size)
class_names = train_ds.class_names
print(class_names)
AUTOTUNE = tf.data.AUTOTUNE
num_classes = len(class_names)
data_augmentation = keras.Sequential(
[
layers.RandomFlip("horizontal",
input_shape=(img_height,
img_width,
3)),
layers.RandomRotation(0.1),
layers.RandomZoom(0.1),
]
)
model = tf.keras.Sequential([
data_augmentation,
tf.keras.layers.Conv2D(64, 3, activation='relu',input_shape=(1,img_height, img_width, 3)),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Conv2D(32, 3, activation='relu'),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Conv2D(16, 3, activation='relu'),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Conv2D(8, 3, activation='relu'),
tf.keras.layers.MaxPooling2D(),
layers.Dropout(0.2),
tf.keras.layers.Flatten(
),
tf.keras.layers.Dense(8, activation='relu'),
tf.keras.layers.Dense(num_classes)
])
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
#model = joblib.load('../h5/model.h5')
history = model.fit(
train_ds,
validation_data=val_ds,
epochs=100
)
model.summary()
joblib.dump(model,'/content/drive/MyDrive/model/model_1.h5')
訓練完成後成果圖:
如果訓練模型上遇到甚麼問題或是error的話歡迎丟到留言區討論喔!
文章主題一覽:
粗體字為額外更新的文章。